package com.zzyl.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.service.WeChatService;
import com.zzyl.utils.ObjectUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;


/**
 * @Description WechatServiceImpl
 * @Author Wen Jie
 * @Date 2024-09-12
 */
@Service
public class WechatServiceImpl implements WeChatService {
    @Value("${zzyl.wechat.appid}")
    private String appid;
    @Value("${zzyl.wechat.appsecret}")
    private String appsecret;
    //获取openId
    private static final String URL_GET_OPENID = "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code";
    // 获取token
    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";

    // 获取手机号
    private static final String PHONE_REQUEST_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";
    @Override
    public String getOpenId(String code) {
        Map<String,Object> requestParams = getAppConfig();
        requestParams.put("js_code",code);
        requestParams.put("grant_type","authorization_code");
        String result = HttpUtil.post(URL_GET_OPENID, requestParams);
        JSONObject jsonObject = JSONUtil.parseObj(result);
        if(ObjectUtil.isNotEmpty(jsonObject.getInt("errcode"))){
            throw new RuntimeException("errmsg");
        }
        return jsonObject.getStr("openid");
    }

    @Override
    public String getPhone(String code) {
        //获取access_token
        String token = getToken();
        if(StringUtils.isEmpty(token)){
            throw new RuntimeException("token为空");
        }
        String url = PHONE_REQUEST_URL+token;

        Map<String,Object> param = new HashMap<>();
        param.put("code",code);

        String result = HttpUtil.post(url, JSONUtil.toJsonStr(param));
        JSONObject jsonObject = JSONUtil.parseObj(result);
        if (jsonObject.getInt("errcode") != 0) {
            //若code不正确，则获取不到phone，响应失败
            throw new RuntimeException(jsonObject.getStr("errmsg"));

        }
        return jsonObject.getJSONObject("phone_info").getStr("purePhoneNumber");

    }


    private Map<String, Object> getAppConfig() {
        Map<String, Object> requestParams = new HashMap<>();
        requestParams.put("appid",appid);
        requestParams.put("secret",appsecret);
        return requestParams;
    }

    public String getToken(){
        Map<String, Object> requestUrlParam = getAppConfig();
        requestUrlParam .put("grant_type","client_credential");

        String result = HttpUtil.get(TOKEN_URL, requestUrlParam);
        //解析
        JSONObject jsonObject = JSONUtil.parseObj(result);

        return jsonObject.getStr("access_token");
    }
}
